package com.lipaluma.excel.io;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import com.lipaluma.exceptions.CsvParserException;
import com.lipaluma.io.Row;
import com.lipaluma.io.SourceWriter;

/**
 * write an Excel file
 * @author mario.soares
 */
public class ExcelWriter implements SourceWriter {
	private OutputStream out;
	private Workbook workbook;
	private Sheet sheet;
	
	private int currentRow = -1;

	/**
	 * Construct an Excel Writer
	 * @param out outputStream for the output result file
	 * @param workbook workbook for writing excel file
	 */
	public ExcelWriter(OutputStream out, Workbook workbook) {
		this(out, workbook, null);
	}

	/**
	 * Construct an Excel Writer
	 * @param out outputStream for the output result file
	 * @param workbook workbook for writing excel file
	 */
	public ExcelWriter(OutputStream out, Workbook workbook, String sheetName) {
		this.out = out;
		this.workbook = workbook;
		if(StringUtils.isNotBlank(sheetName))
			this.sheet = workbook.createSheet(sheetName);
		else
			this.sheet = workbook.createSheet();
	}

	
	public Row createNewRow() {
		org.apache.poi.ss.usermodel.Row row = sheet.createRow(++currentRow);
		return new ExcelRow(workbook, row);
	}
	
	@Override
	public Row duplicateRow(Row row) {
		org.apache.poi.ss.usermodel.Row duplicate = sheet.createRow(++currentRow);
		ExcelRow excelRow = new ExcelRow(workbook, duplicate);
		excelRow.duplicate((ExcelRow)row);
		return excelRow;		
	}
	
	public int getCurrentNumber() {
		return currentRow;
	}
	
	public void close() {
		try {
			workbook.write(out);
			out.close();
		} catch (IOException e) {
			throw new CsvParserException("Error on closing excel file", e);
		}
	}
}
